<template>
    <a-drawer :width="450" :visible="visible" @ok="submit" @cancel="cancel">
        <template #title> {{ $t('shou.quan') }} </template>
        <a-tree
            v-if="treeData.length > 0"
            v-model:checked-keys="checkedKeys"
            :checkable="true"
            :check-strictly="checkStrictly"
            :default-expand-all="defaultExpandAll"
            :field-names="{
                key: 'id',
                title: i18n.global.t('menu.locale'),
                children: 'children',
            }"
            :data="treeData"
        />
    </a-drawer>
</template>

<script setup>
    import { ref } from 'vue';
    import i18n from '@/locale';
    import {
        getPermission,
        getUserPermission,
        editUserPermission,
    } from './service';

    const visible = ref(false);
    const checkStrictly = ref(true);
    const defaultExpandAll = ref(true);
    const checkedKeys = ref([]);
    const treeData = ref([]);
    const userId = ref();

    const fetchData = async (record) => {
        const data = await getPermission();
        treeData.value = data.result || [];
        const data1 = await getUserPermission({ userId: record.id });
        checkedKeys.value = data1.result || [];
    };
    const open = async (record) => {
        visible.value = true;
        checkedKeys.value = [];
        userId.value = record.id;
        await fetchData(record);
    };
    const cancel = () => {
        visible.value = false;
    };
    const submit = async () => {
        try {
            await editUserPermission({
                userId: userId.value,
                menuIds: checkedKeys.value,
            });
        } finally {
            cancel();
        }
    };
    defineExpose({
        open,
    });
</script>

<style lang="less" scoped></style>
